<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of mmw_mapper_Tag
 *
 * @author Manu
 */
require_once("mmw_mapper_Mapper.php");
require_once(dirname(__FILE__) . '/../domain/mmw_domain_Tag.php');

class mmw_mapper_TagMapper extends mmw_mapper_Mapper {
    private $insertStmt;
    private $deleteStmt;
    private $findByTag;
    private $findByTagLike;
    
    public function __construct() {
        parent::__construct();
        
        $this->insertStmt=self::$PDO->prepare(
                "INSERT INTO tags (tag) VALUES (?)");
        $this->deleteStmt=self::$PDO->prepare(
                "DELETE FROM tags WHERE id=?");
        $this->findByTag=self::$PDO->prepare(
                "SELECT * FROM tags WHERE tag=?");
        $this->findByTagLike=self::$PDO->prepare(
                "SELECT * FROM tags WHERE tag LIKE ? ORDER BY tag");                        
    }
    
    public function insert(mmw_domain_DomainObject $object) {
        $values=array($object->getTag());
        $this->insertStmt->execute($values);
        $id=self::$PDO->lastInsertId();
        $object->setId($id);
    }
    
    public function delete($id) {
        $values=array($id);
        $this->deleteStmt->execute($values);        
    }
    
    public function findByTag($tag) {
        $values=array($tag);
        $this->findByTag->execute($values);
        $arResults=$this->findByTag->fetch();
        $this->findByTag->closeCursor();
        
        if (!is_array($arResults)) { return null; }
        else if (!isset($arResults['id'])) { return null; }
        
        $newTag=$this->createObject($arResults);
        return $newTag;
    }
    
    public function findByTagLike($tag) {
        $values=array('%'.$tag.'%');
        $this->findByTagLike->execute($values);
        $arResults=$this->findByTagLike->fetchAll(PDO::FETCH_ASSOC);
        $this->findByTagLike->closeCursor();
        
        if (!is_array($arResults)) { return null; }                        
    
        $arTags=$this->createObjectArray($arResults);
        
        return $arTags;
    }
    
    protected function createObject($array) {
        $tag=new mmw_domain_Tag();
        $tag->setId($array['id']);
        $tag->setTag($array['tag']);
        
        return $tag;
    }
}

?>
